package handler

import (
	"net/http"

	"godco/internal/logic"
	"godco/internal/svc"
	"godco/internal/types"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type Response struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func MergeHookHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		logc.Info(r.Context(), "MergeHookHandler")
		printRequest(r)
		logc.Info(r.Context(), "MergeHookHandler test")
		// 获取特定的请求头
		event := r.Header.Get("X-AtomGit-Event")
		logc.Infof(r.Context(), "AtomGit-Event:%s", event)
		if event == "ping" {
			resp := Response{
				Code:    200,
				Message: "ping ok",
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		if event == "push" {
			resp := Response{
				Code:    200,
				Message: "push ok",
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		var req types.MergeHookRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewMergeHookLogic(r.Context(), svcCtx)
		resp, err := l.MergeHook(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
